package com.edu.controller;

import com.edu.bean.User;
import com.edu.service.BookService;
import com.edu.service.UserService;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @Author:zyn
 * @Date:2025/11/21--11:42:57
 */
@Controller
@Transactional
public class UserController {

    @Resource
    private UserService userService;
    @Resource
    private BookService bookService;
    @RequestMapping("/userLogin")
    public ModelAndView login(String username, String password,
                              @RequestParam(defaultValue = "1") int pageNum,
                              @RequestParam(defaultValue = "10") int pageSize, HttpSession session){
        ModelAndView mv=new ModelAndView();
        Map<String,Object> result=userService.userLogin(username,password);
        Object loginUser = result.get("loginUser");
        if(loginUser !=null){
            // 保存用户登录状态到Session 将完整的用户对象(loginUser)存入Session
            session.setAttribute("loginUser", loginUser);
            // 设置Session过期时间（30分钟）
            session.setMaxInactiveInterval(30 * 60);
            PageInfo pageInfo=bookService.getAllBook(pageNum,pageSize);
            mv.setViewName("book.jsp");
            mv.addObject("pageInfo",pageInfo);
        }else{
            mv.setViewName("login.jsp");
            mv.addObject("msg",result.get("msg"));
        }
        return mv;
    }

    @RequestMapping("/addUser")
    public ModelAndView addUser(String username,String password,String realName){
        ModelAndView mv=new ModelAndView();
        User user=new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setRealName(realName);
        int i = userService.addUser(user);
        if(i==1){
            mv.setViewName("login.jsp");
        }else {
            mv.setViewName("register.jsp");
        }
        return mv;
    }
}
